import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;

/**
 * Created by SEELE on 2018/8/6.
 *
 */
public class U {

    public static void main(String[] args) {
        //using 操作符: 让CloneManFactory产生的CloneMan的生命周期跟随 Observable，Action1是销毁动作
        Observable.using(CloneManFactory.INSTANCE, ObservableFactory.INSTANCE, new Action1<CloneMan>() {
            public void call(CloneMan cloneMan) {
                cloneMan.die();
            }
        });
    }

    public static final class ObservableFactory implements Func1<CloneMan, Observable<String>> {
        static final ObservableFactory INSTANCE;

        static {
            INSTANCE = new ObservableFactory();
        }

        public Observable<String> call(CloneMan cloneMan) {
            return Observable.just(cloneMan.name);
        }
    }

    public static final class CloneManFactory implements Func0<CloneMan> {
        static final CloneManFactory INSTANCE;

        static {
            INSTANCE = new CloneManFactory();
        }

        public CloneMan call() {
            return new CloneMan("DollySheep");
        }
    }

    static final class CloneMan {
        String name;

        CloneMan(String name) {
            this.name = name;
        }

        void die() {
            name = null;
        }
    }
}
